﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Contacts.Mail;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;


namespace Contacts
{
	/// <summary>
	/// Form class for adding or editing companies of contacts
	/// </summary>
    public partial class CompaniesAddEdit : Form
    {
        private DataSet dscont;
        private BindingSource compbs;
        DataGridView dgv;       
        Mess mess;
        string condition;
        int pref;
        public string phone;
        int companyid;
        bool newcompany;
        MySqlConn connect = new MySqlConn();       
        DataTable original = new DataTable();
        DataRow currentrow;
        DataRow origrow;
        DataTable current = new DataTable();
        DataTable currentcomp = new DataTable();
        string timeofpullcomp;
        ContactsAddEdit contform;
        FormCollection forms = Application.OpenForms;
        DataRow company = null;
       
        /// <summary>
        /// this adds a new company
        /// </summary>
        /// <param name="contacts"></param>
        /// <param name="contactsbs"></param>
        /// <param name="tablename"></param>
        /// <param name="grd_jr_cont"></param>
        public CompaniesAddEdit(DataSet contacts, BindingSource contactsbs, string tablename, DataGridView grd_jr_cont)
        {
            InitializeComponent();
            dscont = contacts;
            compbs = contactsbs;
            contactsbs = compbs;
            dgv = grd_jr_cont;
            cbo_categories.DataSource = compbs;
            cbo_categories.ValueMember = "categories.category_id";
            cbo_categories.DisplayMember = "categories.category";
            DataRow cat = contacts.Tables["categories"].NewRow();
            contacts.Tables["categories"].Rows.InsertAt(cat, 0);
            cat["category"] = " ";
            cbo_categories.SelectedIndex = 0;
            cbo_st.AutoCompleteSource = AutoCompleteSource.ListItems;
            cbo_st.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cbo_categories.AutoCompleteSource = AutoCompleteSource.ListItems;
            cbo_categories.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.FormClosed += new FormClosedEventHandler(fclosed);
            this.FormClosing += new FormClosingEventHandler(fclosing);
        }

        private void tbo_comp_Leave(object sender, EventArgs e)
        {
            try
            {
                if (tbo_comp.Text.Length >= 1)
                {
                    string company = tbo_comp.Text.Trim();
                    string[] comp = company.Split(' ');
                    if (comp.Length == 1)
                    { tbo_comp.Text = tbo_comp.Text.Substring(0, 1).ToUpper() + tbo_comp.Text.Substring(1); }

                    else if (comp.Length > 1)
                    {
                        for (int c = 0; c < comp.Length; c++)
                        {
                            comp[c] = comp[c].Substring(0, 1).ToUpper() + comp[c].Substring(1);
                            string jt = string.Join(" ", comp);
                            tbo_comp.Text = jt;
                        }
                    }
                }

                if (!Regex.IsMatch(tbo_comp.Text, @"^[a-zA-Z0-9\-\'\,\&\.\s]{1,100}$") && tbo_comp.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters or length > 100.  " +
                         "Permissible non-alpha characters are (' . &).  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_comp.Clear();
                    tbo_comp.Focus();
                }
            }
            catch (Exception ex)
            {
                string subject = "CompanyForm Company Name Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_comp_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            { ProcessTabKey(true); }
        }


        private void tbo_street_Leave(object sender, EventArgs e)
        {
            try
            {
                connect.Connect("contacts");
                connect.LoadTable("companies", ref currentcomp);

                if (tbo_street.Text.Length >= 1)
                {
                    string street = tbo_street.Text.Trim();
                    string[] str = street.Split(' ');

                    for (int w = 0; w < str.Length; w++)
                    {
                        int i;

                        bool result = int.TryParse(str[w], out i);

                        if (result == false)
                        {
                            str[w] = str[w].Substring(0, 1).ToUpper() + str[w].Substring(1);
                            string jt = string.Join(" ", str);
                            tbo_street.Text = jt;
                        }
                    }
                }

                if (!Regex.IsMatch(tbo_street.Text, @"^[a-zA-Z0-9\-\'\.\s]{1,50}$") && tbo_street.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters or length > 50.  " +
                         "Permissible non-alpha characters are numbers and (' - .).  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_street.Clear();
                    tbo_street.Focus();
                }

                DataRow[] compcompare = currentcomp.Select
                    (string.Format("{0} like '%{1}%' and {2} like '%{3}%'", "company_name",
                    tbo_comp.Text.Replace("'", "''"), "street", tbo_street.Text.Replace("'", "''")));

                if (compcompare != null)
                {
                    int count = compcompare.Count();
                    int i;
                    for (i = 0; i < count; i++)
                    {
                        bool suite = (compcompare[i]["suite"].ToString() != string.Empty);

                        switch (suite)
                        {
                            case true:
                                {
                                    switch (count)
                                    {
                                        case 1:
                                            {
                                                var result = MessageBox.Show("There is (1) company that matched what you entered " +
                                                "in the company and street boxes.\n\n" + compcompare[i]["company_name"] +
                                                "\n" + compcompare[i]["street"] + ", " + compcompare[i]["suite"] +
                                                "\n" + compcompare[i]["city"] + ", " + compcompare[i]["state"] +
                                                " " + compcompare[i]["zip"] + "\n\nDoes this company match what you were " +
                                                "planning on entering?" +
                                                "\n\nThere is a possibility this company was added after your data pull so refresh \n" +
                                                "your data by closing/re-opening contacts after answering question.", "Company Found", MessageBoxButtons.YesNoCancel,
                                                MessageBoxIcon.Question);

                                                switch (result)
                                                {
                                                    case System.Windows.Forms.DialogResult.Yes:
                                                        { this.Close(); }
                                                        return;
                                                    case System.Windows.Forms.DialogResult.No:
                                                        {
                                                            if (i == count)
                                                            { return; }
                                                            break;
                                                        }
                                                    case System.Windows.Forms.DialogResult.Cancel:
                                                        { this.Close(); }
                                                        return;
                                                }
                                            }
                                            break;
                                        default:
                                            {
                                                var result = MessageBox.Show("There are (" + count + ") companies that match what you entered " +
                                                "in the company and street boxes.\n\nHere is record " + (i + 1) + " of those " + count +
                                                " companies.\n\n" + compcompare[i]["company_name"] + "\n" + compcompare[i]["street"] +
                                                ", " + compcompare[i]["suite"] + "\n" + compcompare[i]["city"] + ", " + compcompare[i]["state"] + " " + compcompare[i]["zip"] +
                                                "\n\nDoes this company match what you were planning on entering?" +
                                                "\n\nThere is a possibility this company was added after your data pull so refresh \n" +
                                                "your data by closing/re-opening contacts after answering question.",
                                                "Company Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                switch (result)
                                                {
                                                    case System.Windows.Forms.DialogResult.Yes:
                                                        { this.Close(); }
                                                        return;
                                                    case System.Windows.Forms.DialogResult.No:
                                                        {
                                                            if (i == count)
                                                            { return; }
                                                            break;
                                                        }
                                                    case System.Windows.Forms.DialogResult.Cancel:
                                                        { this.Close(); }
                                                        return;
                                                }
                                            }
                                            break;
                                    }
                                }
                                break;
                            case false:
                                {
                                    switch (count)
                                    {
                                        case 1:
                                            {
                                                var result = MessageBox.Show("There is (1) company that matched what you entered " +
                                                "in the company and street boxes.\n\n" + compcompare[i]["company_name"] +
                                                "\n" + compcompare[i]["street"] + "\n" + compcompare[i]["city"] +
                                                ", " + compcompare[i]["state"] + " " + compcompare[i]["zip"] +
                                                "\n\nDoes this company match what you were planning on entering?" +
                                                "\n\nThere is a possibility this company was added after your data pull so refresh \n" +
                                                "your data by closing/re-opening contacts after answering question.",
                                                "Company Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                switch (result)
                                                {
                                                    case System.Windows.Forms.DialogResult.Yes:
                                                        { this.Close(); }
                                                        return;
                                                    case System.Windows.Forms.DialogResult.No:
                                                        {
                                                            if (i == count)
                                                            { return; }
                                                            break;
                                                        }
                                                    case System.Windows.Forms.DialogResult.Cancel:
                                                        { this.Close(); }
                                                        return;
                                                }
                                            }
                                            break;
                                        default:
                                            {
                                                var result = MessageBox.Show("There are (" + count + ") companies that match what you entered " +
                                                "in the company and street boxes.\n\nHere is record " + (i + 1) + " of those " + count +
                                                " companies.\n\n" + compcompare[i]["company_name"] + "\n" + compcompare[i]["street"] +
                                                "\n" + compcompare[i]["city"] + ", " + compcompare[i]["state"] + " " +
                                                compcompare[i]["zip"] + "\n\nDoes this company match what you were planning on entering?" +
                                                "\n\nThere is a possibility this company was added after your data pull so refresh \n" +
                                                "your data by closing/re-opening contacts after answering question.",
                                                "Company Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                switch (result)
                                                {
                                                    case System.Windows.Forms.DialogResult.Yes:
                                                        { this.Close(); }
                                                        return;
                                                    case System.Windows.Forms.DialogResult.No:
                                                        {
                                                            if (i == count)
                                                            { return; }
                                                            break;
                                                        }
                                                    case System.Windows.Forms.DialogResult.Cancel:
                                                        { this.Close(); }
                                                        return;
                                                }
                                                break;
                                            }
                                    }
                                    break;
                                }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string subject = "CompanyForm Street Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }      
        }

        private void tbo_street_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }

        private void tbo_suite_Leave(object sender, EventArgs e)
        {
            try
            {
                if (tbo_suite.Text.Length >= 1)
                {
                    string suite = tbo_suite.Text.Trim();
                    string[] ste = suite.Split(' ');

                    try
                    {
                        if (ste.Length > 1 && ste.Length <= 2)
                        {
                            for (int s = 0; s < ste.Length; s++)
                            {
                                if (s == 0)
                                {
                                    ste[s].Equals(' ');
                                }

                                else if (s == 1)
                                {
                                    int i;
                                    bool result = int.TryParse(ste[s], out i);
                                    if (result == true)
                                    {
                                        string jt = string.Join(" ", "Suite" + " " + ste[s]);
                                        tbo_suite.Text = jt;
                                        suite_err.Visible = false;
                                    }

                                    else if (result == false)
                                    {
                                        ste[s] = ste[s].Substring(0, ste[s].Length).ToUpper();
                                        string jt = string.Join(" ", "Suite" + " " + ste[s]);
                                        tbo_suite.Text = jt;
                                        suite_err.Visible = false;
                                    }
                                }
                            }
                        }

                        else if (ste.Length == 1)
                        {
                            int i;
                            bool result = int.TryParse(ste[0], out i);
                            if (result == true)
                            {
                                string jt = string.Join(" ", "Suite" + " " + ste[0]);
                                tbo_suite.Text = jt;
                                suite_err.Visible = false;
                            }

                            else if (result == false)
                            {
                                ste[0] = ste[0].Substring(0, ste[0].Length).ToUpper();
                                string jt = string.Join(" ", "Suite" + " " + ste[0]);
                                tbo_suite.Text = jt;
                                suite_err.Visible = false;
                            }
                        }

                        else if (ste.Length > 2)
                        {
                            throw new Exception();
                        }
                    }

                    catch (Exception)
                    {
                        suite_err.Visible = true;
                        suite_err.Text = "Entry is more than 2 words.\nExample:" +
                        " 'Suite 100' or merely '100' gets you 'Suite 100'";
                        suite_err.ForeColor = Color.Red;
                    }
                }

                if (!Regex.IsMatch(tbo_suite.Text, @"^[a-zA-Z0-9'.\s]{1,15}$") && tbo_suite.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters or length > 10.  " +
                         "Permissible non-alpha characters are numbers and (' .).  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_suite.Clear();
                    tbo_suite.Focus();
                }
            }

            catch (Exception ex)
            {
                string subject = "CompanyForm Suite Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_suite_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }

        private void tbo_city_Leave(object sender, EventArgs e)
        {
            try
            {
                if (tbo_city.Text.Length >= 1)
                {
                    string city = tbo_city.Text.Trim();
                    string[] cty = city.Split(' ');

                    if (cty.Length == 1)
                    {
                        tbo_city.Text = tbo_city.Text.Substring(0, 1).ToUpper() + tbo_city.Text.Substring(1);
                    }

                    else if (cty.Length > 1)
                    {
                        for (int i = 0; i < cty.Length; i++)
                        {
                            cty[i] = cty[i].Substring(0, 1).ToUpper() + cty[i].Substring(1);
                            string jt = string.Join(" ", cty);
                            tbo_city.Text = jt;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string subject = "CompanyForm City Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
            
            if (!Regex.IsMatch(tbo_city.Text, @"^[a-zA-Z'.\s]{1,30}$") && tbo_city.Text != "")
            {
                MessageBox.Show("You have entered invalid characters or length > 30.  " +
                     "Permissible non-alpha characters are (').  " +
                     "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                tbo_city.Clear();
                tbo_city.Focus();
            }
        }

        private void tbo_city_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }

        private void cbo_st_Leave(object sender, EventArgs e)
        {
            try
            {

                if (!Regex.IsMatch(cbo_st.Text, @"^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]" +
                    "|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$") && cbo_st.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible characters are CAPITALIZED 2 letter state names.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cbo_st.Focus();
                }
            }
            catch (Exception ex)
            {
                string subject = "CompanyForm State Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_zip_Leave(object sender, EventArgs e)
        {
            try
            {
                if (tbo_zip.Text.Length >= 1)
                {
                    string zip = tbo_zip.Text.Trim();
                    int i;
                    bool result = int.TryParse(zip, out i);
                    if (result == true && zip.Length == 5)
                    { zip = tbo_zip.Text; }

                    else if (result == true && zip.Length == 9)
                    {
                        char[] zipc = zip.ToCharArray(0, 9);
                        string zips = zipc[0].ToString() + zipc[1].ToString() +
                            zipc[2].ToString() + zipc[3].ToString() + zipc[4].ToString() +
                            "-" + zipc[5].ToString() + zipc[6].ToString() + zipc[7].ToString() +
                            zipc[8].ToString();
                        tbo_zip.Text = zips;
                    }

                    else if (result == false && zip.Length == 10)
                    {
                        char[] zipc2 = zip.ToCharArray(0, 10);
                        string zips2 = zipc2[0].ToString() + zipc2[1].ToString() +
                            zipc2[2].ToString() + zipc2[3].ToString() + zipc2[4] +
                            "-" + zipc2[6] + zipc2[7].ToString() + zipc2[8].ToString() +
                            zipc2[9].ToString();
                        tbo_zip.Text = zips2;
                    }
                }

                if (!Regex.IsMatch(tbo_zip.Text, @"^([0-9]{5}(?:-[0-9]{4})?)*$") && tbo_zip.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible numeric with a hyphen.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_zip.Clear();
                    tbo_zip.Focus();
                }
            }
            catch (Exception ex)
            {
                string subject = "CompanyForm Zip Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_zip_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }

        private void tbo_mp1_TextChanged(object sender, EventArgs e)
      {
            string mp1 = tbo_mp1.Text;
            int i;
            bool result = int.TryParse(mp1, out i);
            if (result = true && mp1.Length >= 3)
                if (!Regex.IsMatch(tbo_mp1.Text, @"^[0-9]{1,3}$") && tbo_mp1.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_mp1.Clear();
                    tbo_mp1.Focus();
                }
                else
                {ProcessTabKey(true);}
        }

        private void tbo_mp2_TextChanged(object sender, EventArgs e)
        {
            string mp2 = tbo_mp2.Text;
            int i;
            bool result = int.TryParse(mp2, out i);
            if (result = true && mp2.Length >= 3)
                if (!Regex.IsMatch(tbo_mp2.Text, @"^[0-9]{1,3}$") && tbo_mp2.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_mp2.Clear();
                    tbo_mp2.Focus();
                }
                else
                { ProcessTabKey(true); }
        }

        private void tbo_mp3_TextChanged(object sender, EventArgs e)
        {
            string mp3 = tbo_mp3.Text;
            int i;
            bool result = int.TryParse(mp3, out i);
            if (result = true && mp3.Length >= 4)
                if (!Regex.IsMatch(tbo_mp3.Text, @"^[0-9]{1,4}$") && tbo_mp3.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (4) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_mp3.Clear();
                    tbo_mp3.Focus();
                }
                else
                { ProcessTabKey(true); }
        }

        private void tbo_fax1_TextChanged(object sender, EventArgs e)
        {
            string fax1 = tbo_fax1.Text;
            int i;
            bool result = int.TryParse(fax1, out i);
            if (result = true && fax1.Length >= 3)
                if (!Regex.IsMatch(tbo_fax1.Text, @"^[0-9]{1,3}$") && tbo_fax1.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_fax1.Clear();
                    tbo_fax1.Focus();
                }
                else
                { ProcessTabKey(true); }
        }

        private void tbo_fax2_TextChanged(object sender, EventArgs e)
        {
            string fax2 = tbo_fax2.Text;
            int i;
            bool result = int.TryParse(fax2, out i);
            if (result = true && fax2.Length >= 3)
                if (!Regex.IsMatch(tbo_fax2.Text, @"^[0-9]{1,3}$") && tbo_fax2.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_fax2.Clear();
                    tbo_fax2.Focus();
                }
                else
                { ProcessTabKey(true); }
        }

        private void tbo_fax3_TextChanged(object sender, EventArgs e)
        {
            string fax3 = tbo_fax3.Text;
            int i;
            bool result = int.TryParse(fax3, out i);
            if (result = true && fax3.Length >= 4)
                if (!Regex.IsMatch(tbo_fax3.Text, @"^[0-9]{1,4}$") && tbo_fax3.Text != "")
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (4) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_fax3.Clear();
                    tbo_fax3.Focus();
                }
                else
                { ProcessTabKey(true); }
        }

        private void cbo_categories_SelectedIndexChanged(object sender, EventArgs e)
        {ProcessTabKey(true);}

        //this edits an existing company
        public CompaniesAddEdit(DataSet contacts, BindingSource contactsbs, int compsv, DataGridView grd_jr_cont)
        {
            {
                InitializeComponent();
                dscont = contacts;
                compbs = contactsbs;
                dgv = grd_jr_cont;
                companyid = compsv;                

                cbo_categories.DataSource = compbs;
                cbo_categories.ValueMember = "categories.category_id";
                cbo_categories.DisplayMember = "categories.category";
                DataRow coid = contacts.Tables["companies"].Rows.Find(companyid);               
                tbo_comp.Text = coid["company_name"].ToString();
                tbo_street.Text = coid["street"].ToString();                
                tbo_suite.Text = coid["suite"].ToString();                
                tbo_city.Text = coid["city"].ToString();                
                cbo_st.Text = coid["state"].ToString();                
                tbo_zip.Text = coid["zip"].ToString();
                
                if (!String.IsNullOrEmpty(coid["main_phone"].ToString()))
                {
                    phone = coid["main_phone"].ToString();
                    phone = func.removecharacters(phone);
                    tbo_mp1.Text = func.area(phone);
                    tbo_mp2.Text = func.prefix(phone);
                    tbo_mp3.Text = func.line(phone);
                }                

                if (!String.IsNullOrEmpty(coid["fax"].ToString()))
                {
                    phone = coid["fax"].ToString();
                    phone = func.removecharacters(phone);
                    tbo_fax1.Text = func.area(phone);
                    tbo_fax2.Text = func.prefix(phone);
                    tbo_fax3.Text = func.line(phone);
                }                

                object catsiv = coid["category_id"].ToString();
                DataRow cat = contacts.Tables["categories"].Rows.Find(catsiv);                
                cbo_categories.Text = cat.ItemArray[1].ToString();

                if (func.origcompull == null)
                {
                    original.Columns.Add("company_id", typeof(Int32));
                    original.Columns.Add("company_name");
                    original.Columns.Add("street");
                    original.Columns.Add("suite");
                    original.Columns.Add("city");
                    original.Columns.Add("state");
                    original.Columns.Add("zip");
                    original.Columns.Add("main_phone");
                    original.Columns.Add("fax");
                    original.Columns.Add("category_id", typeof(Int32));
                    original.Columns.Add("timestamp");
                    original.Columns.Add("user");
                    origrow = original.NewRow();
                    origrow["company_id"] = coid["company_id"];
                    origrow["company_name"] = coid["company_name"];
                    origrow["street"] = coid["street"];
                    origrow["suite"] = coid["suite"];
                    origrow["city"] = coid["city"];
                    origrow["state"] = coid["state"];
                    origrow["zip"] = coid["zip"];
                    origrow["main_phone"] = coid["main_phone"];
                    origrow["fax"] = coid["fax"];
                    origrow["category_id"] = cat["category_id"];
                    origrow["timestamp"] = coid["timestamp"];
                    origrow["user"] = coid["user"];
                    original.Rows.Add(origrow);
                    func.origcompull = original;
                }
                else
                {
                    original = func.origcompull;
                }
            }
        }        
        
        public void but_save_Click(object sender, EventArgs e)
        {
            try
            {            
                if (companyid == 0)
                {
                    newcompany = true;
                    company = dscont.Tables["companies"].NewRow();
                    dscont.Tables["companies"].Rows.InsertAt(company, 0);
                    companyid = (int)company.ItemArray[0];
                }
                else if (companyid != 0)
                {
                    company = dscont.Tables["companies"].Rows.Find(companyid);                
                    company["company_id"] = companyid;
                    company.BeginEdit();
                }          

                bool cn = !String.IsNullOrEmpty(tbo_comp.Text);

                switch (cn)
                {
                    case true:
                        {
                            company["company_name"] = tbo_comp.Text;
                        }
                        break;
                    case false:
                        {
                            tbo_comp.BackColor = Color.Red;
                            but_save.Enabled = false;
                        }
                        break;
                }
                
                bool sn = !String.IsNullOrEmpty(tbo_street.Text);

                switch (sn)
                {
                    case true:
                        {company["street"] = tbo_street.Text;}
                        break;
                    case false:
                        {
                            tbo_street.BackColor = Color.Red;
                            but_save.Enabled = false;
                        }
                        break;
                }
                
                bool suite = !String.IsNullOrEmpty(tbo_suite.Text);

                switch (suite)
                {
                    case true:
                        {company["suite"] = tbo_suite.Text;}
                        break;
                    case false:
                        {
                            tbo_suite.BackColor = Color.Green;
                        }
                        break;
                }
                
                bool city = !String.IsNullOrEmpty(tbo_city.Text);

                switch (city)
                {
                    case true:
                        {company["city"] = tbo_city.Text;}
                        break;
                    case false:
                        {
                            tbo_city.BackColor = Color.Red;
                            but_save.Enabled = false;
                        }
                        break;
                }
                
                bool st = !String.IsNullOrEmpty(cbo_st.Text);

                switch (st)
                {
                    case true:
                        {company["state"] = cbo_st.Text;}
                        break;
                    case false:
                        {
                            cbo_st.BackColor = Color.Red;
                            but_save.Enabled = false;
                        }
                        break;
                }

                bool z = !String.IsNullOrEmpty(tbo_zip.Text);

                switch (z)
                {
                    case true:
                        {company["zip"] = tbo_zip.Text;}
                        break;
                    case false:
                        {
                            tbo_zip.BackColor = Color.Red;
                            but_save.Enabled = false;
                        }
                        break;

                }

                bool main = !String.IsNullOrEmpty(tbo_mp1.Text) && !String.IsNullOrEmpty(tbo_mp2.Text) && !String.IsNullOrEmpty(tbo_mp3.Text);

                switch (main)
                {
                    case true:
                        {company["main_phone"] = "(" + tbo_mp1.Text + ")" + " " + tbo_mp2.Text + "-" + tbo_mp3.Text;}
                        break;
                    case false:
                        {
                            tbo_mp1.BackColor = Color.Red;
                            tbo_mp2.BackColor = Color.Red;
                            tbo_mp3.BackColor = Color.Red;
                            but_save.Enabled = false;
                        }
                        break;
                }

                bool fax = !String.IsNullOrEmpty(tbo_fax1.Text) && !String.IsNullOrEmpty(tbo_fax2.Text) && !String.IsNullOrEmpty(tbo_fax3.Text);

                switch (fax)
                {
                    case true:
                        {company["fax"] = "(" + tbo_fax1.Text + ") " + tbo_fax2.Text + "-" + tbo_fax3.Text;}
                        break;
                    case false:
                        {
                            tbo_fax1.BackColor = Color.Green;
                            tbo_fax2.BackColor = Color.Green;
                            tbo_fax3.BackColor = Color.Green;
                        }
                        break;
                }

                bool cate = cbo_categories.Text != " ";

                    switch (cate)
                    {
                        case true:
                            {
                                DataRow cat = dscont.Tables["categories"].Rows.Find(cbo_categories.SelectedValue);
                                company["category_id"] = cat["category_id"];
                            }
                            break;
                        case false:
                            {
                                cbo_categories.BackColor = Color.Red;
                                but_save.Enabled = false;
                            }
                            break;
                    }

                company["timestamp"] = DateTime.Now;
                company["user"] = System.Environment.UserName;
                company["comp_sel"] = tbo_comp.Text + ", " + tbo_street.Text + ", " + tbo_city.Text + ", " + cbo_st.Text;                

                    if ((String.IsNullOrEmpty(tbo_comp.Text) || String.IsNullOrEmpty(tbo_street.Text) || String.IsNullOrEmpty(tbo_city.Text) ||
                        String.IsNullOrEmpty(cbo_st.Text) || String.IsNullOrEmpty(tbo_zip.Text) || String.IsNullOrEmpty(tbo_mp1.Text) ||
                        String.IsNullOrEmpty(tbo_mp2.Text) || String.IsNullOrEmpty(tbo_mp3.Text) || cbo_categories.Text == " ") &&
                        (String.IsNullOrEmpty(tbo_suite.Text) || String.IsNullOrEmpty(tbo_fax1.Text) || String.IsNullOrEmpty(tbo_fax2.Text) ||
                        String.IsNullOrEmpty(tbo_fax3.Text)))
                    {
                        condition = "par";
                        mess = new Mess(condition);
                        mess.Load += new EventHandler(mess_Load);
                        mess.FormClosing += new FormClosingEventHandler(mess_FormClosing);
                        mess.ShowDialog();
                        return;
                    }                

                    else if ((String.IsNullOrEmpty(tbo_comp.Text) || String.IsNullOrEmpty(tbo_street.Text) || String.IsNullOrEmpty(tbo_city.Text) ||
                        String.IsNullOrEmpty(cbo_st.Text) || String.IsNullOrEmpty(tbo_zip.Text) || String.IsNullOrEmpty(tbo_mp1.Text) || 
                        String.IsNullOrEmpty(tbo_mp2.Text) || String.IsNullOrEmpty(tbo_mp3.Text) || cbo_categories.Text == " ") &&
                        (!String.IsNullOrEmpty(tbo_suite.Text) || !String.IsNullOrEmpty(tbo_fax1.Text) || !String.IsNullOrEmpty(tbo_fax2.Text) ||
                        !String.IsNullOrEmpty(tbo_fax3.Text)))
                    {
                        condition = "r";
                        mess = new Mess(condition);
                        mess.Load += new EventHandler(mess_Load);
                        mess.FormClosing += new FormClosingEventHandler(mess_FormClosing);
                        mess.ShowDialog();
                        return;
                    }

                    else if ((!String.IsNullOrEmpty(tbo_comp.Text) || !String.IsNullOrEmpty(tbo_street.Text) || !String.IsNullOrEmpty(tbo_city.Text) ||
                        !String.IsNullOrEmpty(cbo_st.Text) || !String.IsNullOrEmpty(tbo_zip.Text) || !String.IsNullOrEmpty(tbo_mp1.Text) ||
                        !String.IsNullOrEmpty(tbo_mp2.Text) || !String.IsNullOrEmpty(tbo_mp3.Text) || cbo_categories.Text != " ") &&
                        (String.IsNullOrEmpty(tbo_suite.Text) || String.IsNullOrEmpty(tbo_fax1.Text) || String.IsNullOrEmpty(tbo_fax2.Text) ||
                        String.IsNullOrEmpty(tbo_fax3.Text)))                        
                    {                
                        if (pref != 1)
                        {
                            pref = 1;
                            condition = "p";
                            mess = new Mess(condition);
                            mess.Load += new EventHandler(mess_Load);
                            mess.FormClosing += new FormClosingEventHandler(mess_FormClosing);
                            mess.ShowDialog();
                            return;
                        }
                    }                

                string mn = "(" + tbo_mp1.Text + ") " + tbo_mp2.Text + "-" + tbo_mp3.Text;
                string fn = "(" + tbo_fax1.Text + ") " + tbo_fax2.Text + "-" + tbo_fax3.Text;

                company.EndEdit();
                connect.Connect("contacts");
                connect.LoadCompaniesComp(companyid, ref currentcomp);
                if (currentcomp.Rows.Count != 0)
                {
                    currentrow = currentcomp.Rows[0];
                }
                MySqlConn con = new MySqlConn(dscont, dscont.Tables["companies"]);
                con.StatmentCompleted += new MySqlConn.SaveStatementComplete(con_StatmentCompleted);
                connect.StatmentCompleted += new MySqlConn.SaveStatementComplete(con_StatmentCompleted);
                connect.MysqlPreSave(dscont, dscont.Tables["companies"], dgv, company, currentrow, companyid, timeofpullcomp);
                connect.Disconnect();
                this.Dispose();
                Form f = forms["ContactsAddEdit"];
                f.Dispose();
                if (dgv != null)
                {
                    int sel = dgv.NewRowIndex;
                    dgv.Rows[sel].Cells[0].Selected = true;
                }
            }

            catch (Exception ex)
            {
                string subject = "CompanyForm Save Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }  

        private void but_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void mess_FormClosing(object sender, FormClosingEventArgs e)
        {
            Mess mess = (Mess)sender;

            switch (condition)
            {
                case "par":
                    {
                        if (Mess.buttonresult == "ok")
                                {
                                    tbo_comp.BackColor = Color.White;
                                    tbo_street.BackColor = Color.White;
                                    tbo_suite.BackColor = Color.White;
                                    tbo_city.BackColor = Color.White;
                                    cbo_st.BackColor = Color.White;
                                    tbo_zip.BackColor = Color.White;
                                    tbo_mp1.BackColor = Color.White;
                                    tbo_mp2.BackColor = Color.White;
                                    tbo_mp3.BackColor = Color.White;
                                    tbo_fax1.BackColor = Color.White;
                                    tbo_fax2.BackColor = Color.White;
                                    tbo_fax3.BackColor = Color.White;
                                    cbo_categories.BackColor = Color.White;
                                    but_save.Enabled = true;
                                }
                                return;                            
                        }                    

                case "r":
                    {
                        if (Mess.buttonresult == "ok")
                                {
                                    tbo_comp.BackColor = Color.White;
                                    tbo_street.BackColor = Color.White;
                                    tbo_city.BackColor = Color.White;
                                    cbo_st.BackColor = Color.White;
                                    tbo_mp1.BackColor = Color.White;
                                    tbo_mp2.BackColor = Color.White;
                                    tbo_mp3.BackColor = Color.White;
                                    but_save.Enabled = true;
                                }
                                return;                            
                    }

                case "p":
                    {
                        switch (Mess.buttonresult)
                        {
                            case "yes":
                                {
                                    tbo_suite.BackColor = Color.White;
                                    tbo_fax1.BackColor = Color.White;
                                    tbo_fax2.BackColor = Color.White;
                                    tbo_fax3.BackColor = Color.White;
                                }
                                return;
                            
                            case "no":
                                {
                                    but_save.PerformClick();
                                }
                                break;
                        }
                    }
                    break;
            }            
        }

        void con_StatmentCompleted(string SqlStatement)
        {}

        void fclosing(object sender, FormClosingEventArgs e)
        {}

        void fclosed(object sender, FormClosedEventArgs e)
        {}
        
        void mess_Load(object sender, EventArgs e)
        {mess.Load -= new EventHandler(mess_Load);}

        private CompaniesAddEdit()
        {}

        public BindingSource contactbs { get; set; }       
    }
}
